﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CompanyManagement.Models
{
    public class DistrictDAO
    {
        CompanyEntities db;
        public DistrictDAO()
        {
            db = new CompanyEntities();
        }

        public List<District> GetDistricts()
        {
            return db.Districts.Where(p => p.IsActive == true).ToList();
        }

        public bool Insert(District district)
        {
            try
            {
                db.Districts.Add(district);
                db.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Delete(District deleteObj)
        {
            try
            {
                var district = db.Districts.FirstOrDefault(p => p.IsActive == true && p.ID == deleteObj.ID);
                if (district != null)
                {
                    district.IsActive = false;
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        internal bool CheckDistrictInUse(District deleteObj)
        {
            var district = db.Districts.FirstOrDefault(p => p.IsActive == true && p.ID == deleteObj.ID);
            return district.Wards.Any(p=>p.IsActive == true);
        }

        internal bool CheckDistrictExisted(District insertObj)
        {
            return db.Districts.Any(p => p.ID != insertObj.ID && p.IsActive == true && (p.Code.Equals(insertObj.Code) || p.Name.Equals(insertObj.Name)));
        }

        internal District GetDistrictByID(int id)
        {
            return db.Districts.FirstOrDefault(p => p.IsActive == true && p.ID == id);
        }

        internal bool Update(District updateObj)
        {
            try
            {
                var existed = db.Districts.FirstOrDefault(p => p.ID == updateObj.ID && p.IsActive == true);
                if (existed != null)
                {
                    existed.Name = updateObj.Name;

                    db.SaveChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
